package mobi.smarthosts;

import java.util.Date;
import java.util.HashMap;

import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SectionsActivity extends ListActivity {

    public static final String EXTRA_SECTIONS         = "extra_sections";
    public static final String EXTRA_SECTION_NAMES    = "extra_section_names";
    public static final String EXTRA_LAST_UPDATE_DATE = "extra_last_update_date";
    public static final String EXTRA_LAST_UPDATE_MD5  = "extra_last_update_md5";

    private HashMap<String, String> mSections;
    private String[] mSectionNames;
    private Date mLastUpdateDate;
    private String mLastUpdateMD5;

    private boolean mNeedAppendOriginal;

    private SharedPreferences mPref;
//    private Configuration mConf;

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sections);
        mPref = PreferenceManager.getDefaultSharedPreferences(this);
//        mConf = Configuration.init(this);

        mSections = (HashMap<String, String>) getIntent().getSerializableExtra(EXTRA_SECTIONS);
        mSectionNames = getIntent().getStringArrayExtra(EXTRA_SECTION_NAMES);
        mLastUpdateDate = (Date) getIntent().getSerializableExtra(EXTRA_LAST_UPDATE_DATE);
        mLastUpdateMD5 = getIntent().getStringExtra(EXTRA_LAST_UPDATE_MD5);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice, mSectionNames));
        getListView().setItemsCanFocus(false);
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        for (int i = 0; i < getListView().getCount(); i++) getListView().setItemChecked(i, true);

        findViewById(R.id.btn_save).setOnClickListener(mClickListener);
        findViewById(R.id.btn_cancel).setOnClickListener(mClickListener);

        setTitle(getTitle() + " -- " + Utils.formatDateTime(mLastUpdateDate));
    }

    private OnClickListener mClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_save) compositeHostsFile(false);
            finish();
        }
    };

    private void compositeHostsFile(boolean verifyHosts) {
        StringBuilder sb = new StringBuilder(Hosts.META_KEY_SMARTHOSTS_ANDROID);
        SparseBooleanArray checkedItems = getListView().getCheckedItemPositions();
        for (int i=0; i<mSectionNames.length; i++) {
            if (!checkedItems.get(i)) continue;
            Log.d("Appding Hosts section %s", mSectionNames[i]);
            if (mSectionNames[i].equals(getString(R.string.label_original))) {
                mNeedAppendOriginal = true;
                continue;
            }
            sb.append("\n").append(mSections.get(mSectionNames[i])).append("\n");
        }

        // no section is selected, alert user
        if (sb.length() == Hosts.META_KEY_SMARTHOSTS_ANDROID.length()) {
            ViewHelper.showAlertDialog(SectionsActivity.this,
                    getString(R.string.title_default),
                    getString(R.string.msg_noSectionSelected),
                    getString(R.string.label_ok), null);
            return;
        }

        ShellExecutor.rootWriteFile(Configuration.HOSTS_SYSTEM.getAbsolutePath(), sb.toString(), false);

        // Append original hosts if needed.
        if (mNeedAppendOriginal) {
            ShellExecutor.rootAppendFile(Configuration.HOSTS_SYSTEM.getAbsolutePath(),
                    Configuration.HOSTS_ORIGINAL.getAbsolutePath());
        }

        // backup hosts file for toggle
        ShellExecutor.rootCopyFile(Configuration.HOSTS_SYSTEM, Configuration.HOSTS_BAK);

        SharedPreferences.Editor editor = mPref.edit();
        if (mLastUpdateDate != null)
            editor.putLong(PrefKeys.KEY_LAST_UPDATE_DATE, mLastUpdateDate.getTime());
        editor.putString(PrefKeys.KEY_LAST_UPDATE_MD5, mLastUpdateMD5);
        editor.putBoolean(PrefKeys.KEY_USING_SMART_HOSTS, true);
        editor.commit();

        Toast.makeText(this, R.string.msg_reboot, Toast.LENGTH_SHORT).show();

    }

}
